﻿(function ($) {
    $.fn.discover = function (time) {
        if (time == undefined || time == 0 || time == null) {
            time = 5;
        }

        return this.each(function () {

            var that = this;

            var m = new model($(that));
            var v = new view();
            var c = new control(m, v, time);
            c.init();
            c.updateTime();
        })
    }

    var model = function (el) {
        this.el = el;

        this.getAbsoluteLeft = function () {
            var o = this.el.get(0);
            oLeft = o.offsetLeft;
            while (o.offsetParent != null) {
                oParent = o.offsetParent;
                oLeft += oParent.offsetLeft;
                o = oParent;
            }
            return oLeft;
        }

        this.getAbsoluteTop = function () {
            var o = this.el.get(0);
            oTop = o.offsetTop;
            while (o.offsetParent != null) {
                oParent = o.offsetParent;
                oTop += oParent.offsetTop;
                o = oParent;
            }
            return oTop;
        }

        this.getWidth = function () {
            return this.el.css("width");
        }

        this.getHeight = function () {
            return this.el.css("height");
        }

    }

    model.prototype.init = function () {
        this.width = this.getWidth();;
        this.height = this.getHeight();
        this.left = this.getAbsoluteLeft();
        this.top = this.getAbsoluteTop();
    }

    var view = function () {

        this.coverDiv = $("<div>wait:</div>");
        this.coverDiv.css({ "border": "1px solid black", "background-color": "gray", "position": "absolute" });
        this.setCoverdiv = function (model) {
            $(this.coverDiv).css("top", model.top);
            $(this.coverDiv).css("left", model.left);
            $(this.coverDiv).css("width", model.width);
            $(this.coverDiv).css("height", model.height);

            $("body").append($(this.coverDiv));
        }
    }

    var control = function (model, view, time) {
        this.model = model;
        this.view = view;
        this.model.init();
        var that = this;

        this.init = function () {
            this.view.setCoverdiv(this.model);
        }

        this.updateTime = function () {
            if (time == 0) {
                this.view.coverDiv.remove();
                return;
            }
            var val = "wait:" + time;
            this.view.coverDiv.html(val);
            time--;

            var arg = arguments;
            window.setTimeout(function () { arg.callee.apply(that, arg) }, 1000);
        }
    }

})(jQuery);